/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package privileges.bean;

import data_bases.DAO.DatabaseDAO;
import data_bases.beans.TableBean;
import data_bases.business.DataBaseBusiness;
import data_bases.business.Schema;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import privileges.business.SchemaPrivilege;
import privileges.business.User;
import privileges.business.UserBusiness;
import privileges.business.UserDataModel;

/**
 *
 * @author Javier
 */
@ManagedBean(name = "advancedPrivilegesBean")
@SessionScoped
public class AdvancedPrivilegesBean implements Serializable {

    private List<User> users;
    private int index;
    private User selectedUser;
    private UserDataModel mediumUserModel;
    private List<String> selectedStructureOptionsSchema;
    private List<String> selectedDataOptionsSchema;
    private List<String> selectedAdministrationOptionsSchema;
    private List<SchemaPrivilege> schemasPrivileges;
    private List<Schema> schemas;
    private String selectedSchema;
    private String userPrivileges;
    //Propiedades Usuarios
    //colocarlas estaticas
    public String nameUser ;
    public String host;
    //propiedades componentes
    private String disabled;
    private String disabledParent;

    public AdvancedPrivilegesBean() {
        FacesContext context = FacesContext.getCurrentInstance();
        index = 0;
        disabled = "true";  
        users = new ArrayList<>();
        fillList();
        mediumUserModel = new UserDataModel(users);
        selectedSchema = "";
        schemasPrivileges = new ArrayList<>();
        try {
            schemas = new DataBaseBusiness(new DatabaseDAO().viewDatabases()).getSchemas();
        } catch (SQLException ex) {
             context.addMessage(null, new FacesMessage("Error", ex.getLocalizedMessage()));
        }
    }

    public String getUserPrivileges() {
        return userPrivileges;
    }

    public void setUserPrivileges(String userPrivileges) {
        this.userPrivileges = userPrivileges;
    }

    public String getDisabledParent() {
        return disabledParent;
    }

    public void setDisabledParent(String disabledParent) {
        this.disabledParent = disabledParent;
    }

    public String getNameUser() {
        return nameUser;
    }

    public String getDisabled() {
        return disabled;
    }

    public void setDisabled(String disabled) {
        this.disabled = disabled;
    }

    public void setNameUser(String nameUser) {
        this.nameUser = nameUser;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public User getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(User selectedUser) {
        this.selectedUser = selectedUser;
    }

    public UserDataModel getMediumUserModel() {
        return mediumUserModel;
    }

    public void setMediumUserModel(UserDataModel mediumUserModel) {
        this.mediumUserModel = mediumUserModel;
    }

    public List<String> getSelectedStructureOptionsSchema() {
        return selectedStructureOptionsSchema;
    }

    public void setSelectedStructureOptionsSchema(List<String> selectedStructureOptionsSchema) {
        this.selectedStructureOptionsSchema = selectedStructureOptionsSchema;
    }

    public List<String> getSelectedDataOptionsSchema() {
        return selectedDataOptionsSchema;
    }

    public void setSelectedDataOptionsSchema(List<String> selectedDataOptionsSchema) {
        this.selectedDataOptionsSchema = selectedDataOptionsSchema;
    }

    public List<String> getSelectedAdministrationOptionsSchema() {
        return selectedAdministrationOptionsSchema;
    }

    public void setSelectedAdministrationOptionsSchema(List<String> selectedAdministrationOptionsSchema) {
        this.selectedAdministrationOptionsSchema = selectedAdministrationOptionsSchema;
    }

    public List<SchemaPrivilege> getSchemasPrivileges() {
        return schemasPrivileges;
    }

    public void setSchemasPrivileges(List<SchemaPrivilege> schemasPrivileges) {
        this.schemasPrivileges = schemasPrivileges;
    }

    public List<Schema> getSchemas() {
        return schemas;
    }

    public void setSchemas(List<Schema> schemas) {
        this.schemas = schemas;
    }

    public String getSelectedSchema() {
        return selectedSchema;
    }

    public void setSelectedSchema(String selectedSchema) {
        this.selectedSchema = selectedSchema;
    }

    private void fillList() {
        FacesContext context = FacesContext.getCurrentInstance();
        users = new UserBusiness().getUsers();
        if(users.isEmpty() || users == null){
            context.addMessage(null, new FacesMessage("Advertencia", "Usted No cuenta con los permisos Necesarios"));
        }
    }
    
    public String cancel(){
        index = 0;
        disabledParent = "false";
        disabled = "true";
        selectedSchema = "";
        FacesContext fc2 = FacesContext.getCurrentInstance();
        if (fc2.getExternalContext().getSessionMap().containsKey("advancedPrivilegesBean")) {
            System.out.println("entro a borrar adavanced");
            fc2.getExternalContext().getSessionMap().remove("advancedPrivilegesBean");
        }
        FacesContext fc = FacesContext.getCurrentInstance();
        if (fc.getExternalContext().getSessionMap().containsKey("columnPrivilegesBean")) {
            System.out.println("entro a borrar");
            fc.getExternalContext().getSessionMap().remove("columnPrivilegesBean");
        }
        return "principalPage.xhtml?faces-redirect=true";
    }
    //metodo que carga las tablas de los permisos por schema del usuario seleccionado
    public void reloadTables(){
        boolean ok = true;
        getSchemaPri();
        for(SchemaPrivilege  sp: schemasPrivileges){
            if(sp.getSchemaName().equals(selectedSchema.toLowerCase())){
                selectedStructureOptionsSchema = new UserBusiness().getSeStruOp(sp.getSchemaPrivileges());
                selectedDataOptionsSchema = new UserBusiness().getDaOp(sp.getSchemaPrivileges());
                selectedAdministrationOptionsSchema = new UserBusiness().getAdOp(sp.getSchemaPrivileges());
                ok = false;
                break;
             }  
        }
        if(ok){
            if(!(selectedAdministrationOptionsSchema == null)) 
                selectedAdministrationOptionsSchema.clear();
            if(!(selectedStructureOptionsSchema == null ))
                selectedStructureOptionsSchema.clear();
            if(!( selectedDataOptionsSchema == null))
                selectedDataOptionsSchema.clear();
        }
                
    }
    //Boton de continuar "Constructor de los atributos de cada una de las pestañas"
    public void changeTab(){
        FacesContext context = FacesContext.getCurrentInstance();  
        if(selectedUser == null)
            context.addMessage(null,new FacesMessage("Error ","Por favor seleccione un Usuario"));
        else{
            disabledParent = "true";
            disabled = "false";
            index++;
            nameUser = selectedUser.getName();
            host = selectedUser.getHost();
            reloadTables();
            //getSchemaPri();
            context.addMessage(null,new FacesMessage("Exito","Usted seleccionó al usuario "+ nameUser));
         
        }    
    }
    
    //metodo que actualiza los schemas y los privilegios a los cual el usuario seleccionado tiene acceso
    //para cargarlos en la interfaz
    private void getSchemaPri(){
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            schemasPrivileges = 
                new UserBusiness().getSchemaPrivilegesUser(nameUser,host);
        } catch (SQLException ex) {
            context.addMessage(null, new FacesMessage("Error", ex.getLocalizedMessage()));
        }
    }
    public void quitAllPrivileges() {
        FacesContext context = FacesContext.getCurrentInstance();
        if (!(selectedSchema.equals(" "))) {
            if (isSomethingCheck()) {
                    new UserBusiness().doErasePrivileges(selectedSchema,"*", nameUser, host);
                    reloadTables();
                    context.addMessage(null, new FacesMessage("Exito!!!", "Privilegios removidos"));        
            } else {
                context.addMessage(null, new FacesMessage("Error", "Este Schema no contiene ningún permiso"));
            }
        } else {
            context.addMessage(null, new FacesMessage("Error", "Por Favor Seleccione un Schema válido"));
        }
    }
    //metodo que agrega todos los privilegios con un solo botón
    public void addAllPrivileges() {
        FacesContext context = FacesContext.getCurrentInstance();
        if (!(selectedSchema.equals(" "))) {
            try {
                new UserBusiness().addAllPrivileges(selectedSchema, nameUser, host);
                context.addMessage(null, new FacesMessage("Exito!!!", "Privilegios Agregados"));
                reloadTables();
            } catch (SQLException ex) {
                context.addMessage(null, new FacesMessage("Error", ex.getLocalizedMessage()));
            }
        } else {
            context.addMessage(null, new FacesMessage("Error", "Por Favor Seleccione un Schema válido"));
        }
    }
    //Metodo que verifica si esta seleccionado algún permiso
    private boolean isSomethingCheck(){
    System.out.println("que pasa "+selectedAdministrationOptionsSchema.toString()+" "+selectedDataOptionsSchema.toString()+" "+selectedStructureOptionsSchema.toString());
        return (!selectedAdministrationOptionsSchema.isEmpty())
                || (!selectedDataOptionsSchema.isEmpty())
                || (!selectedStructureOptionsSchema.isEmpty()); 
    }
    //Metodo que agrega privilegios que esten seleccionados
    public void addPrivileges() {
        FacesContext context = FacesContext.getCurrentInstance();
        boolean ok = true;
        if (!(selectedSchema.equals(" "))) {
            if (isSomethingCheck()) {
                for (SchemaPrivilege spr : schemasPrivileges) {
                    if (spr.getSchemaName().toLowerCase().equals(selectedSchema.toLowerCase())) {
                        try {
                            SchemaPrivilege sp = new SchemaPrivilege(selectedSchema, new UserBusiness()
                                .constructSchemaPrivileges(selectedStructureOptionsSchema, selectedDataOptionsSchema, selectedAdministrationOptionsSchema));
                            new UserBusiness().doPrivilegesSchemaExist(sp, nameUser, host);
                            context.addMessage(null, new FacesMessage("Exito!!!", "Privilegios agregados"));
                            reloadTables();
                        } catch (SQLException ex) {
                            context.addMessage(null, new FacesMessage("Error", ex.getLocalizedMessage()));
                        }
                        ok = false;
                    }
                }
                if (ok) {
                    try {
                        SchemaPrivilege sp = new SchemaPrivilege(selectedSchema, new UserBusiness()
                                .constructSchemaPrivileges(selectedStructureOptionsSchema, selectedDataOptionsSchema, selectedAdministrationOptionsSchema));
                        new UserBusiness().doPrivilegesSchema(sp, nameUser, host);
                        context.addMessage(null, new FacesMessage("Exito!!!", "Privilegios agregados"));
                        reloadTables();
                    } catch (SQLException ex) {
                        context.addMessage(null, new FacesMessage("Error", ex.getLocalizedMessage()));
                    }
                }
            } else {
                context.addMessage(null, new FacesMessage("Error", "Por Favor al menos seleccione un privilegio"));
            }
        } else {
            context.addMessage(null, new FacesMessage("Error", "Por Favor Seleccione un Schema válido"));
        }
    }
}
